import 'dart:async';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:html/parser.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:yhdm_mobile/page/video/video_entity.dart';

import 'constants.dart';

/// 播放页面
class VideoPage extends StatefulWidget {
  final String url;
  final String name;

  VideoPage(this.name, this.url);

  @override
  _VideoPageState createState() => _VideoPageState();
}

class _VideoPageState extends State<VideoPage> {
  final Completer<WebViewController> _controller =
      Completer<WebViewController>();

  WebViewController myController;

  bool _isVideo = false;

  List<JiEntity> jiList = List();

  JiEntity lastJi;

  bool _isFullScreen = false;

  final Dio dio = Dio();

  @override
  void initState() {
    // 初始化播放列表
    initEpisode();
    super.initState();
  }

  @override
  Widget build(Object context) {
    var size = MediaQuery.of(context).size;
    return WillPopScope(
      onWillPop: () async {
        if (_isFullScreen) {
          toggleFullScreen();
          setState(() {
            _isFullScreen = false;
          });
          return false;
        }
        return true;
      },
      child: Scaffold(
        appBar: _isFullScreen
            ? null
            : AppBar(
                title: Text(widget.name),
              ),
        body: Column(
          children: [
            Container(
              color: Colors.black,
              height: _isFullScreen ? size.height : size.width * .5625,
              width: _isFullScreen ? size.width : size.width,
              child: Stack(
                children: [
                  Opacity(
                    opacity: _isVideo ? 1 : 0,
                    child: WebView(
                      initialUrl: widget.url,
                      javascriptMode: JavascriptMode.unrestricted,
                      onWebViewCreated: (WebViewController controller) async {
                        _controller.complete(controller);
                        myController = controller;
                      },
                      javascriptChannels: <JavascriptChannel>[
                        _dplayerChannel(context),
                      ].toSet(),
                      onPageFinished: (url) async {
                        // 如果是video页面，注入底部控制器的监听
                        if (_isVideo) {
                          setState(() {});
                          injectControllerListener();
                        }
                        // 如果不是video页面，循环遍历查找video地址
                        while (!_isVideo) {
                          var result = await myController.evaluateJavascript(
                              'document.querySelector("#playbox > iframe").src');
                          if (result != null && result != 'null') {
                            // 是视频地址
                            result = result.replaceAll('"', '');
                            print("解析出视频地址：" + result);
                            myController.loadUrl(result);
                            _isVideo = true;
                          } else {
                            print("没有解析出视频地址");
                            sleep(Duration(milliseconds: 200));
                          }
                        }
                      },
                    ),
                  ),
                  Positioned(
                    right: 0,
                    bottom: 0,
                    child: FlatButton(
                      child: Text(''),
                      onPressed: () {
                        toggleFullScreen();
                      },
                    ),
                  ),
                  _isVideo
                      ? Container()
                      : Center(child: CircularProgressIndicator())
                ],
              ),
            ),
            Expanded(
              child: (jiList.isEmpty)
                  ? Container()
                  : Container(
                      child: GridView.builder(
                          padding: EdgeInsets.all(10),
                          itemCount: jiList.length,
                          gridDelegate:
                              SliverGridDelegateWithFixedCrossAxisCount(
                                  childAspectRatio: 2.5,
                                  crossAxisSpacing: 10,
                                  mainAxisSpacing: 10,
                                  crossAxisCount: 4),
                          itemBuilder: (context, index) {
                            return buildJi(jiList[index]);
                          }),
                    ),
            ),
          ],
        ),
      ),
    );
  }

  void toggleFullScreen() {
    if (_isFullScreen) {
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.portraitUp,
        DeviceOrientation.portraitDown,
      ]);
      SystemChrome.setEnabledSystemUIOverlays(
          [SystemUiOverlay.top, SystemUiOverlay.bottom]);
    } else {
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.landscapeLeft,
        DeviceOrientation.landscapeRight,
      ]);
      SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.bottom]);
    }

    setState(() {
      _isFullScreen = !_isFullScreen;
    });
  }

  void injectControllerListener() {
    myController
        .evaluateJavascript('''var target = document.getElementById("dplayer");
var options={
        attributeFilter:['class']//只观察class属性
    };
    var mb=new MutationObserver(function(mutationRecords,observer){
        var target = mutationRecords[0].target;
      if(target.className.indexOf("dplayer-hide-controller") != -1){
        DpldyerChannel.postMessage("hide");
      } else {
        DpldyerChannel.postMessage("show");
      }
    });
    mb.observe(target,options);''');
  }

  JavascriptChannel _dplayerChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'DpldyerChannel',
        onMessageReceived: (JavascriptMessage message) {
          if (message.message == 'hide') {
            // 隐藏了控制器
            if (_isFullScreen) {
              SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.bottom]);
            }
          } else if (message.message == 'show') {
            // 显示了控制器
            if (_isFullScreen) {
              SystemChrome.setEnabledSystemUIOverlays(
                  [SystemUiOverlay.top, SystemUiOverlay.bottom]);
            }
          }
          print(message.message);
        });
  }

  @override
  void dispose() {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
    super.dispose();
  }

  /// 初始化播放列表
  void initEpisode() async {
    var response = await dio.get(widget.url);
    var document = parse(response.data);
    var ul = document.querySelector('#playlists > ul');
    // var video = document.querySelector('#playbox > iframe');
    // var videoUrl= video.attributes['src'];
    // print('videoUrl = $videoUrl');
    ul.children.forEach((element) {
      var classOfLi = element.attributes['class'];
      var status = classOfLi == 'sel' ? 1 : 0;
      var episode = element.firstChild.text;
      var url = 'http://m.yhdm.tv' + element.firstChild.attributes['href'];
      jiList.add(JiEntity(episode, url, status: status));
    });
    setState(() {});
  }

  // List<Widget> buildJis() {
  //   List<Widget> list = List();
  //   jiList.forEach((element) {});
  //   return list;
  // }

  Widget buildJi(JiEntity entity) {
    if (entity.status == 1) {
      lastJi = entity;
    }
    return ActionChip(
      padding: EdgeInsets.zero,
      backgroundColor: getActionColor(entity.status),
      elevation: 3,
      label: Center(
        child: Container(
          child: Text(entity.ji,
              style: TextStyle(
                color: getTextColor(entity.status),
              )),
        ),
      ),
      onPressed: () {
        setState(() {
          _isVideo = false;
          if (lastJi != null) {
            lastJi.status = 2;
          }
          entity.status = 1;
        });
        myController?.loadUrl(entity.url);
        lastJi = entity;
      },
    );
  }

  Color getActionColor(int status) {
    switch (status) {
      case 0:
        return Colors.white;
        break;
      case 1:
        return primaryColor;
        break;
      case 2:
        return Colors.grey;
        break;
      default:
        return Colors.white;
    }
  }

  Color getTextColor(int status) {
    switch (status) {
      case 0:
        return Colors.black;
        break;
      case 1:
        return Colors.white;
        break;
      case 2:
        return Colors.white;
        break;
      default:
        return Colors.white;
    }
  }
}
